﻿Imports ModuloFinanceiro
Imports ModuloEstoque
Imports VendasBLL
Imports VendasDAL
Imports EstoqueBLL
Public Class VendaFRM
    Dim ObjBLL As New VendaBLL
    Dim ObjCliente As New ClientesBLL
    Dim ObjOrdem As New OrdemServicoBLL
    Dim ObjPeca As PECABLL
    Dim ObjServico As ServicoBLL
    Public Codigo, CodCliente, ProCodigo, Status As Integer
    Public Op, Operacao As String
#Region "Métodos"
    Sub CarregaCampos()
        ObjBLL = New VendaBLL(Codigo)
        LBCodigo.Text = "Código: " & ObjBLL.VenCodigo
        ObjCliente = New ClientesBLL(ObjBLL.CodCliente)
        DGVDados.DataSource = ObjBLL.RetItens(Codigo)
        CodCliente = ObjCliente.Codigo
        TXTCliente.Text = ObjCliente.Nome
        If (ObjBLL.Data Is Nothing) Then
            MTBDataEntrada.Text = ""
            MTBHoraEntrada.Text = ""
        Else
            MTBDataEntrada.Text = ObjBLL.Data.Value.Date
            MTBHoraEntrada.Text = Format(ObjBLL.Data, "HH") & Format(ObjBLL.Data, "mm")
        End If
        AtualizaValoreGrid()
        PNProdutos.Enabled = True
        PNOperacaoProduto.Enabled = True
        TSBLocalizarAgendamento.Visible = False
    End Sub

    Sub AtualizaValoreGrid()

        Dim Total As Decimal = "0.00"
        Dim Desconto As Decimal = "0.00"
        Dim VlMaodeObra As Decimal = "0.00"
        For Each col As DataGridViewRow In DGVDados.Rows
            If col.Cells("sta_codigo").Value = 10 Then
                VlMaodeObra += col.Cells("itv_total").Value
            Else
                Total += col.Cells("itv_total").Value
            End If

            Desconto += col.Cells("itv_desconto").Value

        Next
        TXTVlDesconto.Text = Desconto
        TXTVlTotal.Text = (Total + VlMaodeObra) - Desconto
        TXTVlMaoObra.Text = VlMaodeObra
        TXTVlPeca.Text = Total
        TXTVlTotal.Text = FormatCurrency(TXTVlTotal.Text)
        TXTVlDesconto.Text = FormatCurrency(TXTVlDesconto.Text)
        TXTVlPeca.Text = FormatCurrency(TXTVlPeca.Text)
        TXTVlMaoObra.Text = FormatCurrency(TXTVlMaoObra.Text)
    End Sub
    Sub Limpa()
        TXTCliente.Text = ""
        TXTVlDesconto.Text = "R$ 0.00"
        TXTVlMaoObra.Text = "R$ 0.00"
        TXTVlPeca.Text = "R$ 0.00"
        TXTVlTotal.Text = "R$ 0.00"
        If DGVDados.DataSource Is Nothing Then
        Else
            Dim Dt As DataTable
            Dt = DGVDados.DataSource
            Dt.Rows.Clear()
            DGVDados.DataSource = Dt
        End If
        MTBDataEntrada.Text = Date.Now
        MTBHoraEntrada.Text = DateTime.Now.ToString("HH:mm")
        LBCodigo.Text = ""
        PNCLiente.Enabled = True
        PNProdutos.Enabled = False
        PNOperacaoProduto.Enabled = False

    End Sub
    Sub Salva()
        Try
            If (CodCliente > 0) Then
                Dim DataInicial As Nullable(Of DateTime)
                Dim Data As DateTime
                If DateTime.TryParse(MTBDataEntrada.Text & " " & MTBHoraEntrada.Text, Data) Then : DataInicial = Data
                Else : DataInicial = Nothing
                End If
                ObjBLL = New VendaBLL(Codigo, CodCliente, 4, CBFuncionario.SelectedValue, DataInicial, TXTObs.Text)
                If (Op = "I") Then
                    Codigo = ObjBLL.IAEVenda("I")
                    Op = "A"
                Else
                    ObjBLL.IAEVenda("A")
                End If
            Else : Throw New Exception("Informe Cliente")
            End If
        Catch ex As Exception
            Throw
        End Try
    End Sub

    Sub AtualizaValores()

        Dim Total As Decimal = "0.00"
        Dim Desconto As Decimal = "0.00"
        Dim VlMaodeObra As Decimal = "0.00"
        For Each col As DataGridViewRow In DGVDados.Rows
            If col.Cells("sta_codigo").Value = 10 Then
                VlMaodeObra += col.Cells("itv_total").Value
            Else
                Total += col.Cells("itv_total").Value
            End If

            Desconto += col.Cells("itv_desconto").Value

        Next
        TXTVlDesconto.Text = Desconto
        TXTVlTotal.Text = (Total + VlMaodeObra) - Desconto
        TXTVlMaoObra.Text = VlMaodeObra
        TXTVlPeca.Text = Total
        TXTVlTotal.Text = FormatCurrency(TXTVlTotal.Text)
        TXTVlDesconto.Text = FormatCurrency(TXTVlDesconto.Text)
        TXTVlPeca.Text = FormatCurrency(TXTVlPeca.Text)
        TXTVlMaoObra.Text = FormatCurrency(TXTVlMaoObra.Text)
    End Sub
#End Region
#Region "Eventos"

#Region "Pintar datagridview"
    Private Sub DGVDados_RowPrePaint(sender As System.Object, e As System.Windows.Forms.DataGridViewRowPrePaintEventArgs)
        If DGVDados.Rows(e.RowIndex).Index Mod (2) = 1 Then
            DGVDados.Rows(e.RowIndex).DefaultCellStyle.BackColor = Color.Gainsboro
        End If
    End Sub
#End Region

#Region "DatagridView alterar"
    Private Sub DGVDados_CellDoubleClick(sender As System.Object, e As System.Windows.Forms.DataGridViewCellEventArgs)
        TSBALterar_Click(Nothing, Nothing)
    End Sub
#End Region

#Region "DatagridView deletar"
    Private Sub DGVDados_KeyDown(sender As System.Object, e As System.Windows.Forms.KeyEventArgs)
        If (e.KeyCode = Keys.Delete) Then
            TSBExcluir_Click(Nothing, Nothing)
        End If
    End Sub
#End Region

#Region "DatagridView alterar"
    Private Sub DGVDados_KeyPress(sender As System.Object, e As System.Windows.Forms.KeyPressEventArgs)
        If e.KeyChar = Convert.ToChar(Keys.Return) Then
            TSBALterar_Click(Nothing, Nothing)
        End If
    End Sub
#End Region

#Region "Fechar formulário com esc"

    Private Sub OrdemServicoFRM_KeyDown(sender As System.Object, e As System.Windows.Forms.KeyEventArgs)
        If (e.KeyCode = Keys.Escape) Then
            Me.Close()
        End If
    End Sub
#End Region

#Region "Fechar formulário com esc"
    Private Sub VendaFRM_KeyDown(sender As System.Object, e As System.Windows.Forms.KeyEventArgs) Handles MyBase.KeyDown
        If (e.KeyCode = Keys.Escape) Then
            Me.Close()
        End If
    End Sub
#End Region
#End Region
#Region "Códigos não implementados"
    '#Region "Carregar Dinamicamente"
    '    Public Sub carregadinamico()
    '        Try
    '            Dim dt, dt2 As New DataTable
    '            dt = ObjBLL.buscar("", 9)
    '            'dt2 = ObjBLL.buscar("", 8)
    '            'Dim test As Integer
    '            For Each item As DataRow In dt.Rows
    '                If (Val(item("fun_codigo").ToString) > 0) Then
    '                    tvmenu.Nodes.Add(item("fun_nome").ToString, item("fun_nome"))
    '                End If
    '            Next
    '            'For Each subitem As DataRow In dt.Rows
    '            '    test = (Val(subitem("car_codigo").ToString))
    '            '    test = test - 1
    '            '    tvmenu.Nodes(test).Nodes.Add(subitem("fun_codigo").ToString, subitem("fun_nome"))
    '            'Next
    '            'tvmenu.ExpandAll()
    '            tvmenu.TopNode = tvmenu.Nodes(0)
    '        Catch ex As Exception
    '            Throw
    '        End Try
    '    End Sub
    '#End Region

    '#Region "TVMenu_AfterCheck"
    '    Private Sub tvmenu_AfterCheck(sender As System.Object, e As System.Windows.Forms.TreeViewEventArgs)
    '        If (e.Node.Checked = True) Then
    '            For Each item As TreeNode In e.Node.Nodes
    '                item.Checked = True
    '            Next
    '        Else
    '            For Each item As TreeNode In e.Node.Nodes
    '                item.Checked = False
    '            Next
    '        End If
    '    End Sub
    '#End Region
#End Region


#Region "Load"

    Private Sub VendaFRM_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        objconexao.carregaCombo(CBFuncionario, "Vendas.Ofi_Funcionario", "fun_codigo", "fun_nome", "sta_codigo < 3", "fun_nome")
        CBStatus.SelectedIndex = 0
        Limpa()
        If (Op = "I") Then
            TSBLocalizarAgendamento.Visible = True
            Codigo = 0
            CodCliente = 0
        Else
            CarregaCampos()
        End If
    End Sub
#End Region

#Region "Botões"

#Region "Voltar"
    Private Sub TSBVoltar_Click(sender As System.Object, e As System.EventArgs) Handles TSBVoltar.Click
        Me.Close()
    End Sub
#End Region

#Region "Salvar"
    Private Sub TSBSalvar_Click(sender As System.Object, e As System.EventArgs) Handles TSBSalvar.Click
        Try
            Salva()
            MessageBox.Show("Venda gravada com sucesso!", "Atenção", MessageBoxButtons.OK, MessageBoxIcon.Information)
            Me.Close()
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Atenção", MessageBoxButtons.OK, MessageBoxIcon.Information)
        End Try

    End Sub

#End Region


#Region "Localizar Agendamento"
    Private Sub TSBLocalizar_Click(sender As System.Object, e As System.EventArgs) Handles TSBLocalizarAgendamento.Click
        Try
            Dim ObjO As New ConsultaOrdemServico
            ObjO.Tipo = "ret"
            ObjO.ShowDialog()
            If (Not IsNothing(ObjO.ObjO)) Then
                ObjOrdem = ObjO.ObjO
                Op = "A"
                Codigo = ObjBLL.InsereOrdemServico(ObjOrdem.OrdCodigo)
                CarregaCampos()
            End If
        Catch ex As Exception
            Throw
        End Try

    End Sub
#End Region

#End Region

    Private Sub BTNLocalizarCliente_Click(sender As System.Object, e As System.EventArgs) Handles BTNLocalizarCliente.Click
        Dim ObjCC As New ConsultaClientesFRM
        ObjCC.tipo = "ret"
        ObjCC.ShowDialog()
        If (Not IsNothing(ObjCC.ObjC)) Then
            Dim ObjCliente As New ClientesBLL
            ObjCliente = ObjCC.ObjC
            TXTCliente.Text = ObjCliente.Nome
            CodCliente = ObjCliente.Codigo
            ObjCliente = Nothing
            Salva()
            PNProdutos.Enabled = True
            PNOperacaoProduto.Enabled = True
            TSBLocalizarAgendamento.Visible = False
        End If
    End Sub
#Region "Incluir"
    Private Sub TSBIncluir_Click(sender As System.Object, e As System.EventArgs) Handles TSBIncluir.Click
        Try
            Dim Objordem As New OrdemProdutosFRM
            Objordem.VenCodigo = Codigo
            Objordem.Tabela = "Venda"
            Objordem.ShowDialog()
            ObjBLL = New VendaBLL
            DGVDados.DataSource = ObjBLL.RetItens(Codigo)
            AtualizaValores()
            While Objordem.Insere = "+"
                Objordem.ShowDialog()
                DGVDados.DataSource = ObjBLL.RetItens(Codigo)
                AtualizaValores()
                Salva()
            End While
        Catch ex As Exception
            Throw
        End Try
    End Sub
#End Region

#Region "Alterar"
    Private Sub TSBALterar_Click(sender As System.Object, e As System.EventArgs) Handles TSBALterar.Click
        Try
            Dim cod As Integer = 0
            Dim indice As Integer = -1
            For Each linha As DataGridViewRow In DGVDados.SelectedRows
                If (Not linha.Cells("pro_codigo") Is Nothing) Then
                    indice = linha.Index
                End If
            Next
            If (indice <> -1) Then
                OrdemProdutosFRM.Op = "A"
                OrdemProdutosFRM.VenCodigo = (DGVDados.Rows(indice).Cells("ven_codigo").Value)
                OrdemProdutosFRM.ProCodigo = (DGVDados.Rows(indice).Cells("pro_codigo").Value)
                OrdemProdutosFRM.Tabela = "Venda"
                OrdemProdutosFRM.ShowDialog()
                ObjBLL = New VendaBLL
                DGVDados.DataSource = ObjBLL.RetItens(Codigo)
                AtualizaValores()
                Salva()
            Else : Throw New Exception("Selecione o produto/serviço a ser excluido")
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Atenção", MessageBoxButtons.OK, MessageBoxIcon.Information)
        Finally

        End Try
    End Sub
#End Region

#Region "Excluir"
    Private Sub TSBExcluir_Click(sender As System.Object, e As System.EventArgs) Handles TSBExcluir.Click
        Try
            Dim cod As Integer = 0
            Dim indice As Integer = -1
            For Each linha As DataGridViewRow In DGVDados.SelectedRows
                If (Not linha.Cells("sta_descricao") Is Nothing) Then
                    indice = linha.Index
                End If
            Next
            If (indice <> -1) Then
                If MessageBox.Show("Confirma exclusão do produto/serviço: " & DGVDados.Rows(indice).Cells("pro_descricao").Value.ToString() & " ?", "", MessageBoxButtons.YesNo) = vbYes Then
                    Salva()
                    ObjBLL = New VendaBLL(Codigo, DGVDados.Rows(indice).Cells("pro_codigo").Value)
                    ObjBLL.IAEItens("E")
                    ObjBLL = New VendaBLL
                    DGVDados.DataSource = ObjBLL.RetItens(Codigo)
                    AtualizaValores()
                End If
            Else : Throw New Exception("Selecione o produto/serviço a ser excluido")
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Atenção", MessageBoxButtons.OK, MessageBoxIcon.Information)
        Finally
        End Try
    End Sub
#End Region

End Class